var dispatcher = require('../../../util/dispatcher');

var log = console.log;

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

var handler = Handler.prototype;

/**
 * Gate handler that dispatch user to connectors.
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param {Function} next next step callback
 *
 */
handler.queryEntry = function (msg, session, next) {

    // log('连接到gate服务器!');
    // log(msg);

    // 正常的msg
    // msg = {
    //     uid: 'that.userNameEB.string',
    //     __route__: 'gate.gateHandler.queryEntry'
    // };

    // gate 服务器不对不正确请求作回复;
    // if (!msg.__route__ || msg.__route__ !== 'gate.gateHandler.queryEntry') {
    //     return next(null, {});
    // }

    // get all connectors
    var connectors = this.app.getServersByType('connector');
    if (!connectors || connectors.length === 0) {
        next(null, { code: 500 });
        return;
    }

    var res = dispatcher.dispatch(session.id, connectors);
    next(null, {
        code: 200,
        host: res.host,
        port: res.clientPort
    });
};
